﻿using AutoMapper;
using MediatR;
using NPOI.SS.Formula.Functions;
using WMS.Api.Application.Commands.Users;
using WMS.Common;
using WMS.Domain;
using WMS.Infrastructure;
using static Org.BouncyCastle.Crypto.Engines.SM2Engine;

namespace WMS.Api.Application.CommandHandlers.Users
{
    public class AddUserCommandHandler : IRequestHandler<AddUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<User> _userRepo;
        private readonly IMapper _mapper;

        public AddUserCommandHandler(IBaseRepository<User> userRepo,IMapper mapper )
        {
            _userRepo = userRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>("添加用户");

            User user = _mapper.Map<User>(request);

            user.Balance = 0;

            var r =await _userRepo.AddNewAsync(user);

            result.data = r;
            result.isSuc = true;
            result.msg = "添加成功";
            result.code = StatusCodeEnum.Ok;

            if (r<0)
            {
                result.isSuc = false;
                result.data = 0;
                result.msg = "添加失败";
                result.code = StatusCodeEnum.Fail;
            }

            return await Task.FromResult(result);
        }
    }
}
